let retryCount = 0;
const maxRetries = parseInt("{{ configs.get('retry_limit', '3') }}") || 0;

function drawQuestions() {
    const studentId = prompt('请输入学号：');
    if (!studentId) {
        return;
    }

    const formData = new FormData();
    formData.append('student_id', studentId);

    fetch('/draw', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            const questionsList = document.getElementById('questionsList');
            questionsList.innerHTML = '';

            data.data.questions.forEach((question, index) => {
                const card = document.createElement('div');
                card.className = 'card mb-3';
                card.innerHTML = `
                    <div class="card-header">
                        <h6 class="mb-0">题目 ${index + 1}</h6>
                    </div>
                    <div class="card-body">
                        <p class="card-text">${question.content}</p>
                    </div>
                `;
                questionsList.appendChild(card);
            });

            new bootstrap.Modal(document.getElementById('questionsModal')).show();
        } else {
            showError(data.message || '抽题失败，请稍后重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('抽题失败，请稍后重试');
    });
}

function retryDraw() {
    if (maxRetries === 0) {
        showError('当前不允许重抽');
        return;
    }

    if (retryCount >= maxRetries) {
        showError('已达到最大重抽次数');
        return;
    }

    retryCount++;
    fetch('/redraw')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
                return;
            }

            const questionsList = document.getElementById('questionsList');
            questionsList.innerHTML = '';

            data.questions.forEach((question, index) => {
                const card = document.createElement('div');
                card.className = 'card mb-3';
                card.innerHTML = `
                    <div class="card-header">
                        <h6 class="mb-0">题目 ${index + 1}</h6>
                    </div>
                    <div class="card-body">
                        <p class="card-text">${question.content}</p>
                    </div>
                `;
                questionsList.appendChild(card);
            });
        })
        .catch(error => {
            console.error('Error:', error);
            showError('重新抽题失败，请稍后重试');
        });
}

function showError(message) {
    const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
    document.getElementById('errorMessage').textContent = message;
    errorModal.show();
}